/*
 * @Author: blak-kong
 * @Date: 2019-12-03 09:51:44
 * @Email: 546598185@qq.com
 */


// models
const Slideshow = require('../models/Slideshow');
const { SuccessModel, ErrorModel } = require("../models/resModel")

const add = () => {
    // save() 需要先给model赋值实例化
    let doc = new Slideshow({
        name: "",
        img: "",
        url: ""
    })
    doc.save()
}

module.exports = {
    async query (ctx, next) {
        let docs = await Slideshow.find({})
        if (docs) {
            ctx.body = new SuccessModel(docs)
            return
        } else {
            add()
        }
        ctx.body = new SuccessModel({}, "服务器错误！请返回上一页！")
    },
    
    async update (ctx, next) {
        const doc = await Slideshow.findOne({_id: ctx.params.id});
        doc.name = ctx.request.body.name,
        doc.img = ctx.request.body.img,
        doc.url = ctx.request.body.url
        let res = await doc.save()
        if (res.id) {
            ctx.body = new SuccessModel({}, "更新成功！")
            return
        }
        ctx.body = new ErrorModel({}, "更新失败！请稍后重试！")
    },
    async delete (ctx, next) {
        let res = await Slideshow.deleteOne({_id: ctx.params.id})
        if (res.n && res.ok) {
            ctx.body = new SuccessModel({}, "删除成功！")
            return
        }
        ctx.body = new ErrorModel({}, "删除失败！请稍后重试！")
        return
    },

    // async add (ctx, next) {
    //     // save() 需要先给model赋值实例化
    //     let doc = new Slideshow(ctx.request.body)
    //     let res = await doc.save()
    //     if (res.id) {
    //         ctx.body = new SuccessModel({
    //             msg: "创建成功！"
    //         })
    //         return
    //     }
    //     ctx.body = new ErrorModel({})
    // }
}